<?php 
namespace app\admin\controller;

use app\facade\Auth;
use app\facade\Redis;
use app\helps\MoneyHelperBaser;
use app\helps\UserHelper;
use app\models\User as UserModel;
use think\Db;
use think\Exception;
use think\facade\Cache;

class User extends Base
{
    protected function initialize()
    {
        parent::initialize();
        $this->userHelper = new UserHelper();
    }

    public function login_web(){
        $uid = $this->request->param('id');
        $where = array();
        $where["uid"]=$uid;
        $auth = Db::table('tb_user_auth')->where($where)->find();
        if (!$auth){
            $user["real_status"]=-1;
        }else{
            $user["real_status"]=$auth["status"];
            $user["real_name"]=$auth["name"];
        }
//        $wallet = Db::table("tb_wallet")->where('uid', $uid)->where('coin_symbol', "EUSDT")->find();
//        $user['wallet']=$wallet;
        $data= [];
        $data["status"] =1;
        $token =  Auth::set($uid);
        $data["data"]= ['token' =>$token,"user"=>$user];
        $data["url"] =Redis::hget("apk","app_web_url");
        return json($data);
    }

    public function list()
    {
        $obj = Db::table("view_user")->order('id', 'desc');
        $param = $this->request->get();
        if (isset($param['word']) && $param['word']) {
            $obj->where('id|username|contact', "like","%".$param['word']."%");
        }
        if (isset($param['father']) && $param['father']) {
            $obj->where('parent_name', "like","%".$param['father']."%");
        }
        if (isset($param['status']) && $param['status']>-1) {
            $obj->where('status', $param['status']);
        }
        if (isset($param['activity']) && $param['activity']>-1) {
            $obj->where('activity', $param['activity']);
        }
        if (isset($param['start']) && $param['start']) {
            $obj->where('created', '>', $param['start'] . " 00:00:00");
        }
        if (isset($param['end']) && $param['end']) {
            $obj->where('created', '<', $param['end'] . " 00:00:00");
        }
        $list = $obj->paginate(10, false, ['query' => $this->request->param()]);

        $levels = Db::table("tb_mt_level")->select();
        $child_levels = Db::table("tb_mt_level_child")->select();
        return view('', ['list' => $list,'levels' => $levels,'child_levels' => $child_levels]);
    }

    public function status()
    {
        $data = $this->request->post();
        $status = $data['status'] == 0 ? 1 : 0;
        $isOpen = $status == 1 ;
        $maker = $status?"管理员设置用户【启用】":"用户管理员设置【禁用】【未激活】";
        $user = Db::table("tb_user")->where("id", $data['id'])->find();
        $updateResult = $this->userHelper->userStatus($user,$isOpen,$maker);
        if ($updateResult==1) {
            return ['status' => 'y', 'info' => '操作成功'];
        } else {
            return ['status' => 'n', 'info' => '操作失败:'.$updateResult];
        }
    }
    public function userActivity()
    {
        $data = $this->request->post();
        $status = $data['status'] == 0 ? 1 : 0;
        $isOpen = $status == 1 ;
        $maker = $status?"管理员设置用户【激活】":"管理员设置用户【未激活】";
        $user = Db::table("tb_user")->where("id", $data['id'])->find();
        $updateResult = $this->userHelper->userActivity($user,$maker,$isOpen);
        if ($updateResult==1) {
            return ['status' => 'y', 'info' => '操作成功'];
        } else {
            return ['status' => 'n', 'info' => '操作失败:'.$updateResult];
        }
    }

    public function statusRecord()
    {
        $obj = Db::table("tb_user_status_record")->order('id', 'desc');
        $param = $this->request->get();
        if (isset($param['word']) && $param['word']) {
            $obj->where('uid|user_name',"like","%".$param['word']."%");
        }
        $list = $obj->paginate(10, false, ['query' => $this->request->param()]);
        return view('', ['list' => $list]);
    }

    public function profit_status()
    {
        $data = $this->request->post();
        $status = $data['status'] == 0 ? 1 : 0;
        if ((new UserModel)->where('id', $data['id'])->setField('profit_status', $status)) {
            return ['status' => 'y', 'info' => '操作成功'];
        } else {
            return ['status' => 'n', 'info' => '操作失败'];
        }
    }

    public function add(){
        $levels = Db::table("tb_mt_level")->select();

        if ($this->request->isPost()){
            $data = $this->request->post();
            $invite =Db::table("tb_user")->where('username', $data['parent'])->find();
            if (!$invite) {
                return ['status' => 'n', 'info' => '上级账号错误'];
            }

            $lastfather =Db::table("tb_user")->where('id', $invite['parent_id'])->find();
            $lid =0;
            if ($lastfather) {
                $lid=$lastfather['id'];
            }
            if (empty($invite['parents'])){
                $parents = "|".$invite['id']."|";
            }else{
                $parents = $invite['parents'].$invite['id']."|";
            }
            $invite_code = $this->getInviteCode();
            Db::startTrans();
            try {
                $insertData=array(
                    'area'        => 86,
                    'username'    => $data['username'],
                    'mobile'      => $data['username'],
                    'nickname'    => $data['nickname'],
                    'contact'    => $data['contact'],
                    'password'    => md5(md5("123456")),
                    'tradepass'       => md5(md5("123456")),
                    'parent_id'   => $invite['id'],
                    'parent_name' => $invite['username'],
                    'invite_code' => $invite_code,
                    'activity' => 1,
                    'activity_time' => date('Y-m-d H:i:s'),
                    'sys_add' => 1,
                    'parents' => $parents,
                    'lid' => $lid,//上上级id
                );
                $result= Db::table("tb_user")->insertGetId($insertData);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return ['status' => 'n', 'info' => '操作异常：'.$e];
            }
            return ['status' => 'y', 'info' => '操作成功'];
        }

        return view('', ['levels' => $levels]);
    }


    public function edit()
    {
        $uid = $this->request->param('id');
        $row = (new UserModel)->where('id', $uid)->field('id,nickname,username,mobile,contact,weight,level,child_level')->find();
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $level_pass = $this->request->post("level_pass");
            if (!$this->checkLevelPass($level_pass)){
                return ['status' =>'n', 'info' => '操作失败:二级密码错误'];
            }
            $row->contact = $data['contact'];
            $weight = intval($data['weight']);
            $nickname = $data['nickname'];
            $row->weight =$weight>100?100:($weight<0?1:$weight) ;
//            if ($data['mobile']){
//                $row->mobile = $data['mobile'];
//            }else {
//                $row->mobile = '';
//            }
            if ($data['password']) {
                $row->password = $data['password'];
            }
            if ($data['tradepass']) {
                $row->tradepass = md5(md5($data['tradepass']));
            }
            if ($data['nickname']) {
                $row->nickname =$nickname;
            }
            if ($data['level']) {
                $row->level =$data['level'];
            }
            if ($data['level']) {
                $row->child_level =$data['child_level'];
            }
            if ($row->save()) {
                return ['status' => 'y', 'info' => '操作成功'];
            } else {
                return ['status' => 'n', 'info' => '操作成功,数据没有修改'];
            }
        } else {
            $levels = Db::table("tb_mt_level")->select();
            $childlevels = Db::table("tb_mt_level_child")->select();
            return view('', ['row' => $row,'levels' => $levels,'childlevels' => $childlevels]);
        }
    }

    public function feedback()
    {
        $obj = \think\Db::name('feedback')->order('id', 'desc');
        $param = $this->request->get();
        if (isset($param['word']) && $param['word']) {
            $obj->where('uid|uname', $param['word']);
        }
        if (isset($param['status']) && $param['status']) {
            $obj->where('status', 0);
        }
        $list = $obj->paginate(10, false, ['query' => $this->request->param()]);
        return view('', ['list' => $list]);
    }

    public function feedback_edit()
    {
        $model = \think\Db::name('feedback');
        $id = $this->request->param('id');
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $model->where('id', $id)->update([
                'reply_msg' => $data['reply_msg'],
                'reply_time' => date('Y-m-d H:i:s'),
                'status' => 1
            ]);
            return ['status' => 0, 'info' => '操作成功'];
        } else {
            $row = $model->where('id', $id)->find();
            return view(null, ['data' => $row]);
        }
    }

    public function wallte()
    {
        $uid = $this->request->param('uid');
        $wallets = Db::table("tb_wallet")->where("uid",$uid)->select();
        return view(null, ['rows' => $wallets,'uid' => $uid]);
    }

    public function tree()
    {
        $pid=$this->request->param("id");
        $user = Db::table("tb_user")->field("username ,level ,activity ,id")->where("id",$pid)->find();
        $data =  $this->getTree($pid);
        $user["title"]= "账号：".$user["username"]. " 团队等级：".$user["level"].($user["activity"]==0?" 未激活":" 已激活");
        if ($data){
            $user["children"] =$data;
        }
        return view('', ['data' => [$user]]);
    }

    private function getTree($pid){
        $users = Db::table("tb_user")->field("username ,level ,activity ,id")->where("parent_id",$pid)->select();
//        echo  "pid = " .$pid ." size  =" .count($users) ."\n";
        if ($users){
            foreach ($users as $index=>$user){
//                echo  "uid = " .$user["id"] ."\n";
                $users[$index]["title"]= "账号：".$user["username"]. " 团队等级：".$user["level"].($user["activity"]==0?" 未激活":" 已激活");
                $childs = $user["id"]==0?null:$this->getTree($user["id"]);
                if ($childs){
                    $users[$index]["children"] =$childs;
                }
            }
        }else{
            return null;
        }
        return $users;
    }

    public function auth()
    {
        $data = $this->request->post();
        UserModel::where('id', $data['id'])->setField($data['field'], $data['status']);
        return ['status' => 'y', 'info' => '操作成功'];
    }

    public function carry()
    {
        $obj = \think\Db::name('carry')->order('id', 'desc');
        $param = $this->request->param();
        if (isset($param['status']) && $param['status']) {
            $obj->where('status', $param['status']);
        }
        if (isset($param['start']) && $param['start']) {
            $obj->where('created', '>', $param['start'] . " 00:00:00");
        }
        if (isset($param['end']) && $param['end']) {
            $obj->where('created', '<', $param['end'] . " 00:00:00");
        }
        $list = $obj->paginate(10, false, ['query' => $this->request->param()]);
        return view('', ['list' => $list]);
    }
    public function carry_edit()
    {
        $id = $this->request->param('id');
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $carry = \think\Db::name('carry')->where('id', $id)->find();
            if ($carry['status'] != 1) {
                return ['status' => 'n', 'info' => '订单已处理'];
            }

            \think\Db::name('carry')->where('id', $id)->update([
                'info' => $data['info'],
                'status' => $data['status'],
            ]);
            // 驳回
            if ($data['status'] == 3) {
                $user = UserModel::get($carry['uid']);
                integralLog::create([
                    'uid' => $user['id'],
                    'uname' => $user['username'],
                    'act' => 1,
                    'type' => 20,
                    'num' => $carry['num'] + $carry['fee'],
                    'end_num' => $user['integral'] + $carry['num'] + $carry['fee'],
                    'info' => 'AYB提现驳回',
                    'order_id' => $carry['id'],
                ]);
                $user->setInc('integral', $carry['num'] + $carry['fee']);
            }
            return ['status' => 0, 'info' => '操作成功'];
        } else {
            $row = \think\Db::name('carry')->where('id', $id)->find();
            return view(null, ['data' => $row]);
        }
    }
    public function report()
    {
        $obj = Report::order('id', 'desc');
        $param = $this->request->param();
        if (isset($param['status']) && $param['status']) {
            $obj->where('type', $param['status']);
            $sum = $obj->sum('num');
        }
        if (isset($param['start']) && $param['start']) {
            $obj->where('created', '>', $param['start'] . " 00:00:00");
        }
        if (isset($param['end']) && $param['end']) {
            $obj->where('created', '<', $param['end'] . " 00:00:00");
        }

        if (isset($param['word']) && $param['word']) {
            $obj->where('uid', $param['word']);
            $teamName = UserModel::get($param['word']);
            $sum = $obj->sum('num');
        }

        $list = $obj->paginate(10, false, ['query' => $this->request->param()]);
        return view('', [
            'list' => $list,
            'type' => Report::getType(),
            'sum' => isset($sum) ? $sum : 0,
            'username' => isset($teamName) ? $teamName->username : '',
        ]);
    }
    public function profitDay(){
        $obj = Db::table("tb_profit_day")->order('receive', 'asc')->order('id', 'desc');
        $param = $this->request->get();
        if (isset($param['word']) && $param['word']) {
            $obj->where('uid', $param['word']);
        }
        if (isset($param['receive']) && $param['receive']>0) {
            $obj->where('receive', $param['receive']);
        }
        if (isset($param['start']) && $param['start']) {
            $obj->where('time', '>', strtotime($param['start']));
        }
        if (isset($param['end']) && $param['end']) {
            $obj->where('time', '<', strtotime($param['end']));
        }

        $list = $obj->paginate(10, false, ['query' => $this->request->param()]);

        return view('', ['list' => $list]);
    }

    public function nameAuthList()
    {
        $obj = Db::table("view_auth")->order('status', 'asc')->order('id', 'desc');
        $param = $this->request->get();
        if (isset($param['word']) && $param['word']) {
            $obj->where('uid', $param['word']);
        }
        if (isset($param['username']) && !empty($param['username'])) {
            $obj->where('username', $param['username']);
        }
        if (isset($param['mobile']) && !empty($param['mobile'])) {
            $obj->where('mobile', $param['mobile']);
        }
        if (isset($param['word']) && $param['word']) {
            $obj->where('uid|username|mobile', $param['word']);
        }
        if (isset($param['status']) && $param['status']>-1) {
            $obj->where('status', $param['status']);
        }
        if (isset($param['start']) && $param['start']) {
            $obj->where('time', '>', strtotime($param['start']));
        }
        if (isset($param['end']) && $param['end']) {
            $obj->where('time', '<', strtotime($param['end']));
        }
        $list = $obj->paginate(10, false, ['query' => $this->request->param()]);

        return view('', ['list' => $list]);
    }

    public function nameAuthStatus()
    {
        $data = $this->request->post();
        $auth = Db::table("tb_user_auth")->where('id', $data['id'])->find();
        $uid = $auth["uid"];
        $phone = Db::table('tb_user')->where("id",$uid)->value("mobile");
        $list = Db::table('tb_user')->where("mobile",$phone)->select();
        Db::startTrans();
        try{
            foreach ($list as $item){
                $updateData = array();
                $updateData['status'] = $data['status'];
                $res = Db::table("tb_user_auth")->where('uid', $item['id'])->update($updateData);
                if (!$res){
                    Db::rollback();
                    return ['status' => 'n', 'info' => '操作失败:'.Db::table("tb_user_auth")->getLastSql()];
                }
            }
            Db::commit();
            return ['status' => 'y', 'info' => '操作成功'];
        }catch (\Exception $e) {
            Db::rollback();
            return ['status' => 'n', 'info' => '操作失败'.$e->getMessage()];
        }
    }

    public function sysUserList()
    {
        $obj = Db::table("tb_mt_sysuser")->order('id', 'desc');
        $param = $this->request->get();
        if (isset($param['word']) && $param['word']) {
            $obj->where('user_name|mobile',"like" ,"%".$param['word']."%");
        }
        $list = $obj->paginate(10, false, ['query' => $this->request->param()]);

        return view('', ['list' => $list]);
    }

    public function sysUserEdit()
    {

        $id = $this->request->param('id');
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (empty($data["mobile"])){
                return ['status' => "n", 'info' => '请填写手机号'];
            }
            if (empty($data["user_name"])){
                return ['status' => "n", 'info' => '请填写姓名'];
            }
            $data["create_time"]=date("Y-m-d H:i:s");
            if ($id > 0) {
                $bool = Db::table("tb_mt_sysuser")->where('id',$id)->update($data);
            } else {
                $bool = Db::table("tb_mt_sysuser")->insert($data);
            }
            return ['status' => "y", 'info' => '操作成功'];
        }
        $row = Db::table("tb_mt_sysuser")->where('id', $id)->find();
        return view(null, ['data' => $row]);
    }

    public function imageShow()
    {
        $data = $this->request->get();
        return view('', ['url' => $data['src']]);
    }

    public function usersells()
    {
        $goods = Db::table("tb_mt_good")->select();
        $obj = Db::table("tb_mt_sell")->order('id', 'desc');
        $param = $this->request->get();
        $obj->where('uid', $param['id']);
        $obj->whereIn('status', '1,3,4,6');
        if (isset($param['word']) && $param['word']) {
            $obj->where('sn', "like","%".$param['word']."%");
        }
        if (isset($param['type']) && $param['type']>-1) {
            $obj->where('type', $param['type']);
        }

        if (isset($param['gid']) && $param['gid']>0) {
            $obj->where('gid', $param['gid']);
        }
        if (isset($param['start']) && $param['start']) {
            $obj->where('create_time', '>', $param['start'] . " 00:00:00");
        }
        if (isset($param['end']) && $param['end']) {
            $obj->where('create_time', '<', $param['end'] . " 00:00:00");
        }

        if (isset($param['outstart']) && $param['outstart']) {
            $obj->where('estimate', '>', $param['outstart'] . " 00:00:00");
        }
        if (isset($param['outend']) && $param['outend']) {
            $obj->where('estimate', '<', $param['outend'] . " 00:00:00");
        }
        $list = $obj->paginate(10, false, ['query' => $this->request->param()]);
//        echo $obj->getLastSql();
        return view('', ['list' => $list,'goods' => $goods]);
    }

    public function recharge()
    {
        $uid = $this->request->param('id');
        $user = UserModel::get($uid);
        if ($this->request->isPost()){
            $data = $this->request->post();
            if (!is_numeric($data['num'])) {
                return ['status' => 'n', 'info' => '数量错误'];
            }
            if (!$uid) {
                return ['status' => 'n', 'info' => 'uid错误'];
            }
            $num = $data['num'];
            $field_name= $data['field_name'];
            $helper = new MoneyHelperBaser();

            Db::startTrans();
            try{
                $res = $helper->sysUser($user,floatval(round($num,2)),$field_name);
                if ($res==1){
                    Db::commit();
                    return ['status' => 'y', 'info' => '充值成功'];
                }
                Db::rollback();
                return ['status' => 'n', 'info' => '充值错误'.$res];
            }catch (Exception $e){
                return ['status' => 'n', 'info' => '充值异常'.$e->getMessage()];
                Db::rollback();
            }

        }
        return view('', ['data' => $user]);
    }

    private function getInviteCode(){
        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0,25)]
            .strtoupper(dechex(date('m')))
            .date('d').substr(time(),-5)
            .substr(microtime(),2,5)
            .sprintf('%02d',rand(0,99));
        for(
            $a = md5( $rand, true ),
            $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
            $d = '',
            $f = 0;
            $f < 8;
            $g = ord( $a[ $f ] ),
            $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
            $f++
        );
        return  $d;
    }
}
